package com.xingchen.feima.gateway.filter;

import com.xingchen.feima.common.utils.JwtHelper;
import com.xingchen.feima.gateway.config.AuthProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * <p>
 * 1.根据配置文件中的excludePaths，判断当前请求是否需要拦截
 * 2.判断token是否合法，如果合法，则将用户信息保存到请求头中，给下游微服务使用
 * </p>
 *
 * @author yangxc
 * @since 2025-02-11
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private AuthProperties authProperties;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取request
        ServerHttpRequest request = exchange.getRequest();
        // 2.请求path和excludePaths匹配，进行放行
        if(isPass(request.getPath().toString())){
            // 放行
            return chain.filter(exchange);
        }
        // 3.对于需要拦截的，获取token
        String token = null;
        List<String> tokenList = request.getHeaders().get("token");
        if (tokenList != null && !tokenList.isEmpty()) {
            token = tokenList.get(0);
        }

        // 4.校验并解析token
        Long userId = null;
        try {
            userId = JwtHelper.getUserId(token);
        } catch (Exception e)
        {
            // 拦截，设置响应状态码为401
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 5.将用户信息保存到请求头，给下游微服务使用
        if (userId == null) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        String userInfo = userId.toString();
        ServerWebExchange newExchange = exchange.mutate()
                .request(builder -> builder.header("user-info", userInfo))
                .build();
        // 6.放行
        return chain.filter(newExchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private boolean isPass(String path) {
        for (String pathPattern : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(pathPattern, path)) {
                return true;
            }
        }
        return false;
    }
}

